//
//  CarNewsCollectionViewCell.m
//  小汽车
//
//  Created by 杜远洋 on 14-12-29.
//  Copyright (c) 2014年 蓝欧科技. All rights reserved.
//

#import "CarNewsCollectionViewCell.h"
#import "CarNewsTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "CarNewsModel.h"
#import "SpecialCarTableViewCell.h"
#import "UIScrollView+MJRefresh.h"

#import "Masonry.h"
#import "AFJSONRequestOperation.h"
@implementation CarNewsCollectionViewCell
- (void)dealloc
{
 
    [_tableArray release];
    [_tableView release];
    [super dealloc];
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.tableArray = [NSMutableArray array];
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, COLLECTION_CELL_WIDTH, COLLECTION_CELL_HEIGHT - 140) style:UITableViewStylePlain];
        [self.tableView setBackgroundColor:[UIColor clearColor]];
        NSLog(@"tableview = %@",self);
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        [self.tableView registerClass:[CarNewsTableViewCell class] forCellReuseIdentifier:@"cell1"];
         [self.tableView registerClass:[SpecialCarTableViewCell class] forCellReuseIdentifier:@"cell2"];
        [self.tableView setRowHeight:COLLECTION_CELL_HEIGHT / 3 - 17];
        
        [self.contentView addSubview: self.tableView];
        [_tableView release];
        
        //第一次显示的cell个数
        self.count = 10;
        [self SetUpRefresh];
    }
    return self;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
#pragma mark - 切记这个地方不可以改为count，因为当你滑动页面的时候，count还会保持原来的大小，就会造成数组越界的错误
    
    return [self.tableArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 
    CarNewsModel *model = [self.tableArray objectAtIndex:indexPath.row];
    self.newsIndex = model.markedId;
    if (model.markedId == 2) {
        [self.tableView setRowHeight:COLLECTION_CELL_HEIGHT / 8];
        SpecialCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        cell.highlighted = NO;
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.dateLabel setText:model.createDates];
        [cell.titleLabel setText:model.newsTitle];
     
        return cell;
        
    }
    else
    {
    CarNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    cell.highlighted = NO;
#pragma mark - 设置为选中时无点击效果
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.carImage setImageWithURL:[NSURL URLWithString:model.newsImg_small] placeholderImage:[UIImage imageNamed:@"placeHolder.png"] options:SDWebImageRetryFailed];
    [cell.dates setText:model.createDates];
    [cell.descriptions setText:model.newsTitle];
    [cell.replyCounts setText:model.comments];
    
    return cell;
    }
    
}







- (void)SetUpRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(downLoad)];
    // #warning 自动刷新(一进入程序就下拉刷新)
   // [self.tableView headerBeginRefreshing];
    
    //2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    if ([self.tableArray count] < 100) {
        [self.tableView addFooterWithTarget:self action:@selector(upLoad)];
    }
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开立即刷新了";
    self.tableView.headerRefreshingText = @"正在刷新中";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开立即加载更多数据";
    self.tableView.footerRefreshingText = @"正在加载中";
}


- (void) downLoad
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
    
}


- (void) upLoad
{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        self.count += 10;
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self connectUrlWhileLoding];
        [self.tableView footerEndRefreshing];
    });
    
    
    
    
}
#pragma mark - 当刷新的时候调用网页链接，加载数据 ，往新添加的cell里加入数据
- (void)connectUrlWhileLoding
{
   
  
   
    NSString *myUrl = [NSString stringWithFormat:@"http://wap.xcar.com.cn/cms/interface/5.0/getNewsList.php?limit=10&offset=%ld&type=%ld&ver=5.3.4",(self.count - 10), self.newsIndex];
    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
    NSURL *url = [NSURL URLWithString:[myUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        if (self.newsIndex != 2) {
           
            NSArray *array = [JSON objectForKey:@"news"];
            
            for (NSDictionary *dic in array) {
                CarNewsModel *model = [[CarNewsModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                NSNumber *comment = [dic objectForKey:@"comment"];
                NSString *myComment = [NSString stringWithFormat:@"%@",comment];
                model.comments = myComment;
                model.createDates = [self getLocalTime];
                [self.tableArray addObject:model];
                [model release];
            }
            
            [self.tableView reloadData];
            
            
        }
        else
        {
          
            NSArray *array = [JSON objectForKey:@"news"];
            
            for (NSDictionary *dic in array) {
                CarNewsModel *model = [[CarNewsModel alloc] init];
                model.newsTitle = [dic objectForKey:@"newsTitle"];
                model.newsLink = [dic objectForKey:@"newsLink"];
                model.markedId = 2;
                model.createDates = [self getLocalTime];
                [self.tableArray addObject:model];
                [model release];
                
            }
            
            [self.tableView reloadData];
        }
        
 
        [self.tableView footerEndRefreshing];
        
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"数据链接失败。。。");
        NSLog(@"%@", error);
    }];
    [operation start];
}

#pragma mark - 获取本地时间

- (NSString *)getLocalTime
{
    NSDate *dates = [NSDate date];
    NSDateFormatter *formatter =  [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/beijing"];
    [formatter setTimeZone:timeZone];
    NSString *localTime = [formatter stringFromDate:dates];
    NSLog(@"loctime = %@",localTime);
    return localTime;
}


#pragma mark - 点击的时候调用代理，然后在代理的实现方法里进行页面跳转，因为自定义的collectionView不能跳转页面

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CarNewsModel *model = [self.tableArray objectAtIndex:indexPath.row];
    if (model.markedId == 2) {
        [self.delegate changePage:model.newsLink];
     
    }
    else
    {
        [self.delegate changePage:model.newsLink];
        
    }
    

}


#pragma mark - 设置不同的高度，因为cell格式不一样

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CarNewsModel *model = [self.tableArray objectAtIndex:indexPath.row];
    if (model.markedId == 2) {
        return COLLECTION_CELL_HEIGHT/8;
    }
    else
    {
        return COLLECTION_CELL_HEIGHT *5 / 29;
    }
}






@end
